<template>
  <ma-form-item
    v-if="typeof props.component.display == 'undefined' || props.component.display === true"
    :component="props.component"
    :custom-field="props.customField"
  >
    <slot :name="`form-${props.component.dataIndex}`" v-bind="props.component">
      <a-textarea
        v-model.trim="value"
        :allow-clear="props.component.allowClear ?? true"
        :auto-size="props.component.autoSize"
        :disabled="props.component.disabled"
        :error="props.component.error"
        :max-length="props.component.maxLength"
        :placeholder="props.component.placeholder ?? `请输入${props.component.title}`"
        :readonly="props.component.readonly"
        :show-word-limit="props.component.showWordLimit"
        :size="props.component.size"
        :word-length="props.component.wordLength"
        :word-slice="props.component.wordSlice"
        @blur="rv('onBlur')"
        @change="rv('onChange', $event)"
        @clear="rv('onClear')"
        @focus="rv('onFocus')"
        @input="rv('onInput', $event)"
      >
      </a-textarea>
    </slot>
  </ma-form-item>
</template>

<script setup>
import { get, set } from "lodash";
import MaFormItem from "./form-item.vue";
import { runEvent } from "@/components/MaForm/types/event";

const props = defineProps({
  component: Object,
  customField: { type: String, default: undefined }
});

const formModel = inject("formModel");
const getColumnService = inject("getColumnService");
const columns = inject("columns");
const rv = async (ev, value = undefined) =>
  await runEvent(
    props.component,
    ev,
    {
      formModel,
      getColumnService,
      columns
    },
    value
  );

const index = props.customField ?? props.component.dataIndex;
const value = ref(get(formModel.value, index));

watch(
  () => get(formModel.value, index),
  vl => (value.value = vl)
);
watch(
  () => value.value,
  v => {
    set(formModel.value, index, v);
    index.indexOf(".") > -1 && delete formModel.value[index];
  }
);

rv("onCreated");
onMounted(() => rv("onMounted"));
</script>
